'use strict';

exports.main = async (event, context) => {
  const db = uniCloud.database();
  const { taskId, adminId } = event;

  if (!taskId) {
    return {
      code: 400,
      msg: '缺少任务ID',
      data: null
    };
  }

  try {
    const taskCollection = db.collection('taskList');
    
    // 先获取任务信息用于日志记录
    const taskResult = await taskCollection.doc(taskId).get();
    if (!taskResult.data || taskResult.data.length === 0) {
      return {
        code: 404,
        msg: '任务不存在',
        data: null
      };
    }

    const task = taskResult.data[0];

    // 删除任务
    const deleteResult = await taskCollection.doc(taskId).remove();

    // 记录删除日志
    const auditLogCollection = db.collection('audit_logs');
    await auditLogCollection.add({
      target_type: 'task',
      target_id: taskId,
      action: 'deleted',
      admin_id: adminId || 'admin',
      task_info: {
        title: task.title,
        publisher_id: task.publisher_id,
        publisher_name: task.publisher_name,
        reward: task.reward
      },
      create_time: new Date()
    });

    // 如果任务有关联的聊天记录，也可以选择删除或标记
    try {
      const chatCollection = db.collection('chatMessages');
      await chatCollection.where({
        taskId: taskId
      }).update({
        task_deleted: true,
        delete_time: new Date()
      });
    } catch (chatError) {
      console.log('更新聊天记录失败:', chatError);
    }

    return {
      code: 200,
      msg: '任务删除成功',
      data: {
        taskId: taskId,
        deleted: deleteResult.deleted
      }
    };
  } catch (error) {
    console.error('删除任务失败:', error);
    return {
      code: 500,
      msg: '删除任务失败',
      data: null
    };
  }
};
